<!--
 * @Author: your name
 * @Date: 2021-04-06 15:45:10
 * @LastEditTime: 2021-04-08 10:01:50
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /Interview Files/大纲/1106去重排序.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组去重、排序</title>
</head>

<body>

</body>

</html>
<script>
    let arr2 = [2, 5, 3, 7, 5, 1, 4, 6, 3, 4, 5, 6, 3, 2, 5, 7];
    document.write(`去重数组:[${arr2}]`);
    // 去重方式1:splice
    function unique(arr) {
        for (let i = 0; i < arr.length; i++) {
            for (let j = i + 1; j < arr.length; j++) {
                if (arr[i] === arr[j]) {
                    arr.splice(j, 1);
                    j--;
                }
            }
        }
        return arr
    };
    document.write(`<br>使用splice方式:[${unique(arr2)}]`);


    // 去重方式2:indexOf
    function unique1(arr) {
        let arr1 = [];
        for (let i = 0; i < arr.length; i++) {
            if (arr1.indexOf(arr[i]) == -1) {
                arr1.push(arr[i]);
            }
        }
        return arr1
    };
    document.write(`<br>使用indexOf方式:[${unique1(arr2)}]`)

    // 去重方式3:Set
    function unique2(arr) {
        return Array.from(new Set(arr));
    };
    document.write(`<br>使用ES6 Set方式:[${unique2(arr2)}]`);


    let arr = [22, 34, 13, 54, 13, 87, 65, 15, 8, 2];
    document.write(`<br>排序数组:[${arr}]`);

    function sorts(arr) {
        for (let i = 0; i < arr.length - 1; i++) {
            for (let j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    let tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                }
            }
        }
        return arr;
    };
    document.write(`<br>使用冒泡排序:[${sorts(arr)}]`);

    function sortNumber(a, b) {
        return a - b
    };
    document.write(`<br>使用sort排序:[${arr.sort(sortNumber)}]`);
</script>